//
//  OrderFoodViewController.m
//  MyProject
//
//  Created by yun on 2018/8/13.
//  Copyright © 2018年 yun. All rights reserved.
//

#import "OrderFoodViewController.h"
#import "LeftTableViewCell.h"
#import "RightTableViewCell.h"
#import "RightHeaderView.h"

@interface OrderFoodViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong) UITableView *leftTableView;
@property(nonatomic,strong) UITableView *rightTableView;

@property(nonatomic,strong) NSMutableArray *leftArray;
@property(nonatomic,strong) NSMutableArray *rightArray;

@property(nonatomic,assign) BOOL scrollDown;// 是否向下滑动（加载更多信息）


@end

@implementation OrderFoodViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.leftArray = [NSMutableArray array];
    self.rightArray = [NSMutableArray array];
    
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"meituan" ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:filePath];
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSArray *foods = dict[@"data"][@"food_spu_tags"];
    
    for (NSDictionary *dic in foods) {
        GoodsModel *model1 = [GoodsModel mj_objectWithKeyValues:dic];
        NSMutableArray *spusArray = [NSMutableArray array];
        for (NSDictionary *spus in model1.spus) {
            GoodsDetailsModel *model2 = [GoodsDetailsModel mj_objectWithKeyValues:spus];
            [spusArray addObject:model2];
        }
        [self.leftArray addObject:model1];
        [self.rightArray addObject:spusArray];
    }
    
    self.leftTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.leftTableView.delegate = self;
    self.leftTableView.dataSource = self;
    [self.view addSubview:self.leftTableView];
    [self.leftTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.equalTo(self.view);
        make.width.mas_equalTo(100);
    }];
    
    [self.leftTableView registerNib:[UINib nibWithNibName:@"LeftTableViewCell" bundle:nil] forCellReuseIdentifier:LeftCellReuseIdentifier];
    
    [self.leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionTop];
    
    self.rightTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.rightTableView.delegate = self;
    self.rightTableView.dataSource = self;
    [self.view addSubview:self.rightTableView];
    [self.rightTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.bottom.equalTo(self.view);
        make.left.equalTo(self.leftTableView.mas_right);
    }];
    [self.rightTableView registerNib:[UINib nibWithNibName:@"RightTableViewCell" bundle:nil] forCellReuseIdentifier:RightCellReuseIdentifier];
    [self.rightTableView registerClass:[RightHeaderView class] forHeaderFooterViewReuseIdentifier:HeaderReuseIdentifier];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (tableView == _leftTableView) {
        return 1;
    } else {
        return _rightArray.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == _leftTableView) {
        return _leftArray.count;
    } else {
        return [_rightArray[section] count];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _leftTableView) {
        return 50;
    } else {
        return 80;
    }
}

static NSString * const LeftCellReuseIdentifier = @"LeftCellReuseIdentifier";
static NSString * const RightCellReuseIdentifier = @"RightCellReuseIdentifier";
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _leftTableView) {
        LeftTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LeftCellReuseIdentifier forIndexPath:indexPath];
        if (_leftArray.count > indexPath.row) {
            GoodsModel *model = _leftArray[indexPath.row];
            cell.nameLabel.text = model.name;
        }
        return cell;
    } else {
        RightTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:RightCellReuseIdentifier forIndexPath:indexPath];
        if (_rightArray.count > indexPath.row) {
            [cell setupInfoWithModel:_rightArray[indexPath.section][indexPath.row]];
        }
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _leftTableView) {
        NSIndexPath *ipath = [NSIndexPath indexPathForRow:0 inSection:indexPath.row];
        [self.rightTableView scrollToRowAtIndexPath:ipath atScrollPosition:UITableViewScrollPositionTop animated:YES];
        
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (tableView == _rightTableView) {
        return 30;
    } else {
        return 0;
    }
    
}

static NSString * const HeaderReuseIdentifier = @"HeaderReuseIdentifier";
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (tableView == _rightTableView) {
        RightHeaderView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderReuseIdentifier];
        if (_leftArray.count > section) {
            GoodsModel *model = _leftArray[section];
            header.nameLabel.text = model.name;
        }
        return header;
    }
    return nil;
}
/**
 * 根据是向上滑动还是向下滑动来调整左侧滑动的策略。
 
 向上滑动（查看上面的信息）:头视图是悬浮在section上的，所以向上滑动将要显示上个section的时候，左侧tableview滑动到当前位置
 向下滑动（查看下面的信息）:向下滑动，是要在上个头视图消失的时候，左侧tableview滑动下一个位置。故要+1
 */
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section{
    if (tableView == _rightTableView && (_rightTableView.dragging || _rightTableView.decelerating) && !_scrollDown) {
        [self.leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:section inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
    }
}

- (void)tableView:(UITableView *)tableView didEndDisplayingHeaderView:(UIView *)view forSection:(NSInteger)section{
    if (tableView == _rightTableView && (_rightTableView.dragging || _rightTableView.decelerating) && _scrollDown) {
        [self.leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:section+1 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    static CGFloat offset = 0;
    if (scrollView == _rightTableView) {
        _scrollDown = offset < scrollView.contentOffset.y;
        offset = scrollView.contentOffset.y;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
